package com.dev.springBootDemo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class FieldCounter {

    /**
     * 统计指定文件中的指定字段出现次数及行号（模糊匹配）
     *
     * @param filePaths 文件路径列表
     * @param fieldName 需要统计的字段名称
     * @return 包含每个文件中字段出现次数和行号的映射
     */
    public static Map<String, Map<Integer, Integer>> countFieldOccurrencesWithLineNumbers(List<String> filePaths, String fieldName) {
        Map<String, Map<Integer, Integer>> fieldCountMap = new HashMap<>();
        Pattern pattern = Pattern.compile(Pattern.quote(fieldName));

        for (String filePath : filePaths) {
            Map<Integer, Integer> lineCountMap = new HashMap<>();
            int totalCount = 0;
            int lineNumber = 0;
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    lineNumber++;
                    Matcher matcher = pattern.matcher(line);
                    int countInLine = 0;
                    while (matcher.find()) {
                        countInLine++;
                    }
                    if (countInLine > 0) {
                        totalCount += countInLine;
                        lineCountMap.put(lineNumber, countInLine);
                    }
                }
            } catch (IOException e) {
                System.err.println("Error reading file " + filePath + ": " + e.getMessage());
            }
            fieldCountMap.put(filePath, lineCountMap);
            fieldCountMap.get(filePath).put(-1, totalCount); // -1 表示总次数
        }

        return fieldCountMap;
    }

    public static void main(String[] args) throws IOException {
        Path directoryPath = Paths.get("D:\\data\\245");
        List<String> filePaths = Files.walk(directoryPath)
                .filter(Files::isRegularFile)
                .map(Path::toString)
                .filter(path -> path.endsWith(".log"))
                .collect(Collectors.toList());

        // String fieldName = "【流程中心】当前登录用户";
        String fieldName = "java.lang.IndexOutOfBoundsException";

        Map<String, Map<Integer, Integer>> result = countFieldOccurrencesWithLineNumbers(filePaths, fieldName);

        int globalTotalCount = 0;

        for (Map.Entry<String, Map<Integer, Integer>> fileEntry : result.entrySet()) {
            System.out.println("File: " + fileEntry.getKey());
            Map<Integer, Integer> lineCounts = fileEntry.getValue();
            for (Map.Entry<Integer, Integer> lineEntry : lineCounts.entrySet()) {
                if (lineEntry.getKey() == -1) {
                    globalTotalCount += lineEntry.getValue();
                    System.out.println("Total occurrences in this file: " + lineEntry.getValue());
                } else {
                    System.out.println("Line " + lineEntry.getKey() + ": " + lineEntry.getValue() + " occurrences");
                }
            }
            System.out.println();
        }

        System.out.println("Global total occurrences: " + globalTotalCount);
    }
}
